var amapApp = angular.module('AMapApp',[]);

amapApp.directive('pages', [function(){
	return {
		controller: function($scope, $element, $attrs, $transclude) {
			var pages = [];
			var that = this;

			this.addPage = function(page){
				pages.push(page);
			};

			this.getPageCount = function(){
				return pages.length;
			};


			this.setActivePage = function(pageName){
				angular.forEach(pages, function (page) {
					if(page.nid == pageName){
						page.show = true;
					}else{
						page.show = false;
					}
				});
			};

			$scope.$on('pageChange',function(event,data){
				that.setActivePage(data);
			});
		},
		restrict: 'A',
		transclude: true,
		replace:true,
		template:'<div ng-transclude></div>'
	};
}]);

amapApp.directive('page', [function(){
	return {
		require: '^?pages',
		restrict: 'A',
		scope:{
			nid:'@id'
		},
		controller:function ($scope, $element, $attrs, $transclude) {
			$scope.show = false;
			$scope.toggle = function(){
				$scope.show  = !$scope.show ;
			};
		},
		template:'<div ng-show="show" ng-transclude></div>',
		replace: true,
		transclude: true,
		link: function($scope, iElm, iAttrs, controller) {
			var count = controller.getPageCount();
			if(count == 0){
				$scope.show = true;
			}

			controller.addPage($scope);
		}
	};
}]);

amapApp.run(['$rootScope', function($rootScope){
	$rootScope.data = {
		location:{
			longitude:113.358169,
			latitude:23.135021
		}
	};
}]);

amapApp.controller('MapController', ['$scope','$rootScope','$location','$anchorScroll','$timeout','$cacheFactory',
	function($scope,$rootScope,$location,$anchorScroll,$timeout,$cacheFactory){
	$scope.data = {
		isLocating:false,
		isZoomOutEnable:true,
		isZoomInEnable:true
	};

	$scope.mapInit = function () {
		var searchMap = new SearchMap();
	    searchMap.init({
	        elementId:'mapCon',
	        locateSuccessCb:$scope.locateSuccessCb,
	        locateErrorCb:$scope.locateErrorCb
	    });

	    $rootScope.searchMap = searchMap;
	};

	$scope.locate = function () {
		$scope.data.isLocating = true;
		// $scope.searchMap.getCurrentPosition();
		$timeout(function () {
			$rootScope.data.location = {
				longitude:113.358169,
				latitude:23.135021
			};
			$scope.locateSuccessCb($rootScope.data.location);
		},1000);
	};

	$scope.locateSuccessCb = function (data) {
		$scope.$apply(function () {
			$scope.data.isLocating = false;
			$rootScope.searchMap.centerAt($rootScope.data.location);
		});
	};

	$scope.locateErrorCb = function (data) {
		$scope.$apply(function (data) {
			$scope.data.isLocating = false;
		});
	};

	$scope.zoomIn = function (argument) {
		var maxZoom = $rootScope.searchMap.getMaxZoom();
		var zoom = $rootScope.searchMap.getZoom();
		if(maxZoom == zoom + 1){
			$scope.data.isZoomInEnable = false;
		}else{
			$scope.data.isZoomInEnable = true;
		}

		$rootScope.searchMap.zoom(true);
	};

	$scope.zoomOut = function (argument) {
		var minZoom = $rootScope.searchMap.getMinZoom();
		var zoom = $rootScope.searchMap.getZoom();
		if(minZoom == zoom - 1){
			$scope.data.isZoomOutEnable = false;
		}else{
			$scope.data.isZoomOutEnable = true;
		}

		$rootScope.searchMap.zoom(false);
	};


	$scope.clear = function () {
		$rootScope.searchMap.clear();
		$rootScope.$broadcast('clear');
	};
}]);

amapApp.controller('SearchController', ['$scope','$rootScope', '$location',
	'$anchorScroll','$timeout','$http','$cacheFactory',
	function($scope,$rootScope,$location,$anchorScroll,$timeout,$http,$cacheFactory){
	$scope.data = {
		keyword:"",
		isError:false,
		message:""
	};

	var timer = null;
	$scope.change = function (name) {
		if(name == ""){
			$scope.data.isError = false;
			$scope.data.pois = [];
			return;
		}

		$timeout.cancel(timer);
		timer = $timeout(function(data) {
			AMap.service(["AMap.PlaceSearch"], function() {
				var searcher = new AMap.PlaceSearch({
					city: '广州市'
				});

				searcher.search(name, function(status, result) {
					if (status == 'error') {
						alert("服务请求出错啦！ ");
					}
					if (status == 'no_data') {
						alert("无数据返回，请换个关键字试试～～");
					} else {
						if(!result.info || result.info != "OK"){
							$scope.$apply(function () {
								$scope.data.isError = true;
								$scope.data.message = result.info;
							});
						}else{
							$scope.$apply(function () {
								$scope.data.isError = false;
								$scope.data.pois = result.poiList.pois;
							});
						}
					}
				});
			});
		}, 500);
	};

	$scope.locate = function (item) {
		$scope.$emit('pageChange','main');
		$rootScope.data.location = {longitude:item.location.getLng(),latitude:item.location.getLat()};
		$rootScope.searchMap.centerAt($rootScope.data.location);
	};

}]);

amapApp.controller('MoreController', ['$scope','$rootScope', '$location',
	'$anchorScroll','$timeout','$http','$cacheFactory',
	function($scope,$rootScope,$location,$anchorScroll,$timeout,$http,$cacheFactory){
		$scope.getGeocode = function () {

		};

}]);

amapApp.controller('SearchAroundController', ['$scope','$rootScope', '$location',
	'$anchorScroll','$timeout','$http','$cacheFactory',
	function($scope,$rootScope,$location,$anchorScroll,$timeout,$http,$cacheFactory){
	$scope.data = {};

	$scope.searchAround = function (typeName) {
		AMap.service(["AMap.PlaceSearch"], function() {
		    var searcher = new AMap.PlaceSearch({
		         city:'广州',
		         type:typeName,
		         extensions: "all"
		    });

	        searcher.searchNearBy("*",new AMap.LngLat($rootScope.data.location.longitude, $rootScope.data.location.latitude),
	        	500, function(status, result){
	            if(status=='error') {
	                alert("服务请求出错啦！ ");
	            }
	            if(status=='no_data') {
	                alert("无数据返回，请换个关键字试试～～");
	            }
	            else {
	            	console.log(result);
	            	$scope.$apply(function () {
	            		$scope.data.pois = result.poiList.pois;
	            	});
	            }
	        });
	    });
	}

	$scope.locate = function (item) {
		$scope.$emit('pageChange','main');
		$rootScope.data.location = {longitude:item.location.lng,latitude:item.location.lat};
		$rootScope.searchMap.centerAt($rootScope.data.location);
	};
}]);

amapApp.controller('PlanController', ['$scope','$rootScope', '$location',
	'$anchorScroll','$timeout','$http','$cacheFactory',
	function($scope,$rootScope,$location,$anchorScroll,$timeout,$http,$cacheFactory){
	$scope.data = {
		type: 2,
		isError: false,
		starts: [],
		ends: [],
		start: {},
		end: {},
		result: {}
	};

	$scope.clear = function (argument) {
		if($scope.data.result.routes && $scope.data.result.routes.length > 0){
			$scope.data.result = {};
			$rootScope.searchMap.clear();
		}
	}

	var timer = null;
	$scope.change = function(name, destListName) {
		$scope.clear();

		if (name == "" || name == undefined) {
			$scope.data.isError = false;
			if (destListName == 'starts') {
				$scope.data.starts = [];
			} else {
				$scope.data.ends = [];
			}
			return;
		}

		$timeout.cancel(timer);
		timer = $timeout(function(data) {
			AMap.service(["AMap.PlaceSearch"], function() {
				var searcher = new AMap.PlaceSearch({
					city: '广州市'
				});

				searcher.search(name,function(status, result) {
					if (status == 'error') {
						alert("服务请求出错啦！ ");
					}
					if (status == 'no_data') {
						alert("无数据返回，请换个关键字试试～～");
					} else {
						if (!result.info || result.info != "OK") {
							$scope.$apply(function() {
								$scope.data.isError = true;
								$scope.data.message = result.info;
							});
						} else {
							if (destListName == 'starts') {
								$scope.$apply(function() {
									$scope.data.isError = false;
									$scope.data.starts = result.poiList.pois;
								});
							} else {
								$scope.$apply(function() {
									$scope.data.isError = false;
									$scope.data.ends = result.poiList.pois;
								});
							}
						}
					}
				});
			});
		}, 500);
	};

	$scope.select = function(item, srcListName) {
		if (srcListName == 'starts') {
			$scope.data.start = item;
			$scope.data.starts = [];
		} else {
			$scope.data.end = item;
			$scope.data.ends = [];
		}
	};

	$scope.search = function() {
		if ($scope.data.type == 2) {
			AMap.service(["AMap.Walking"], function() {
				var searcher = new AMap.Walking();

				searcher.search($scope.data.start.location,$scope.data.end.location,
					function(status, result) {
						if (status == 'error') {
							alert("服务请求出错啦！ ");
						}
						if (status == 'no_data') {
							alert("无数据返回，请换个关键字试试～～");
						} else {
							$scope.$apply(function() {
								$scope.data.result = result;
							});

							if(result.routes.length > 0){
								var polylines = [];
								angular.forEach(result.routes[0].steps, function(item) {
									polylines = polylines.concat(item.path);
								});

								$rootScope.searchMap.addRoute({
									path: polylines,
									strokeWeight:4,
									strokeColor:'blue'
								});

								var startPoint = result.routes[0].steps[0].path[0];
								var endPoint = result.routes[0].steps[result.routes[0].steps.length-1].path[result.routes[0].steps[result.routes[0].steps.length-1].path.length - 1];
								$rootScope.searchMap.addStartMarker(startPoint.getLng(),startPoint.getLat());
								$rootScope.searchMap.addEndMarker(endPoint.getLng(),endPoint.getLat());
							}
						}
					});
			});
		}
	};

	$scope.checkStep = function(step) {
		$rootScope.searchMap.addSegment({
			path: step.path,
			strokeColor: 'red',
			strokeWeight:6
		});

		$scope.$emit('pageChange','main');

		$rootScope.searchMap.focus();
	};

	$scope.$on('clear',function (argument) {
		$scope.clear();

		$scope.data.start = {};
		$scope.data.end = {};
	})
}]);